﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace wUniAppPCL.MVVM
{

  public class BaseCollectionViewModel<T> : wObservableObject
  {
    public BaseCollectionViewModel()
    {
      Items = new ObservableCollection<T>();
    }

    protected virtual void OnSelectedItemChanged(SelectedItemChangedEventArgs<T> selectedItemChangedEventArgs)
    {
      var handler = SelectedItemChanged;
      if (handler != null)
      {
        handler(this, selectedItemChangedEventArgs);
      }
    }

    public event EventHandler<SelectedItemChangedEventArgs<T>> SelectedItemChanged;

    public ObservableCollection<T> Items { get; set; }

    protected T selectedItem;
    [XmlIgnore]
    public T SelectedItem
    {
      get { return selectedItem; }
      set
      {
        var old = selectedItem;
        if (SetProperty(ref selectedItem, value, "SelectedItem"))
        {
          OnSelectedItemChanged(
            new SelectedItemChangedEventArgs<T>() { OldValue = old, NewValue = selectedItem }
          );
        }
      }
    }
  }
  

  public class SelectedItemChangedEventArgs<T> : EventArgs
  {
    public T OldValue { get; set; }
    public T NewValue { get; set; }
  }
}
